import type { RouteRecordRaw } from 'vue-router'

// 动态获取所有的路由对象, 放到数组中
// * 路由对象都在独立的文件中
// * 从文件中将所有路由对象先读取数组中
export function loadFilesRoute() {
  const files: Record<string, any> = import.meta.glob('@/router/main/**/*.ts', {
    eager: true
  })
  // 将路由文件的路径放到数组里
  const loadLocalRoutes: RouteRecordRaw[] = []
  for (const key in files) {
    const module = files[key]
    loadLocalRoutes.push(module.default)
  }
  return loadLocalRoutes
}
// 点击登录的时候默认展示的菜单
export let firstMenu: any = null
// 根据角色不同的菜单动态添加路由
export function mapAddRouter(userMenus: any) {
  const loadLocalRoutes = loadFilesRoute()
  const route: RouteRecordRaw[] = []
  for (const menu of userMenus) {
    for (const subItem of menu.children) {
      const routes = loadLocalRoutes.find((item) => item.path === subItem.url)
      // 类型缩小
      if (routes) {
        // 给route的顶层菜单添加重定向功能(只添加一次)
        if (!route.find((item) => item.path === subItem.url)) {
          route.push({
            path: menu.url,
            redirect: routes.path
          })
        }
        route.push(routes)
      }
      if (!firstMenu && routes) firstMenu = subItem
    }
  }
  return route
}

export function mapPathMenu(path: string, userMenus: any[]) {
  for (const menu of userMenus) {
    for (const subitem of menu.children) {
      if (path == subitem.url) {
        return subitem
      }
    }
  }
}
// 面包屑
export function mapPathBreadCrumb(path: string, userMenus: any[]) {
  const pathBreadCrumb: any = []
  for (const menu of userMenus) {
    for (const subitem of menu.children) {
      if (path == subitem.url) {
        pathBreadCrumb.push({ path: menu.url, name: menu.name })
        pathBreadCrumb.push({ path: subitem.url, name: subitem.name })
      }
    }
  }
  return pathBreadCrumb
}

// 用递归映射到id的列表
export function mapMenuIds(menuList: any[]) {
  const ids: number[] = []

  function getMenusIds(menus: any[]) {
    for (const item of menus) {
      if (item.children) {
        getMenusIds(item.children)
      } else {
        ids.push(item.id)
      }
    }
  }
  getMenusIds(menuList)
  return ids
}

// 映射菜单权限
export function mapMenuAuthority(menuList: any[]) {
  const authority: string[] = []

  function mapForMenu(menu: any[]) {
    for (const menuAuth of menu) {
      if (menuAuth.type === 3) {
        authority.push(menuAuth.permission)
      } else {
        mapForMenu(menuAuth.children ?? [])
      }
    }
  }

  mapForMenu(menuList)
  return authority
}
